"""
#!/usr/bin/env python
# -*- coding:utf-8 -*-
@Project : 界面
@File : U_Real2Local_Dialog.py
@Author : RuanYaoHuang
@Time : 2023/2/16 16:57
"""

# !/usr/bin/env Python
# coding=utf-8
import cv2
from PIL.Image import open

from base64 import b64encode
from os import remove
from sqlite3 import connect
from io import BytesIO

from qdarkstyle import load_stylesheet_pyqt5
from PyQt5.QtGui import QPixmap, QImage, QTransform
from PyQt5.QtCore import pyqtSignal, Qt, QDateTime, QTimer, QDir
from PyQt5.QtMultimedia import QCameraInfo
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QVBoxLayout, QGridLayout, QApplication, QGroupBox, \
	QLabel, QComboBox, QPushButton, QMessageBox, QSpacerItem, QSizePolicy, QFileDialog, QDesktopWidget

from U_Target_view import Target_view
from U_Loc_img_view_Dialog import Loc_Sim_Matplot_Dialog

from matplotlib.pyplot import rcParams
rcParams['font.sans-serif'] = ['SimHei']
rcParams['axes.unicode_minus'] = False


class Realtime_view(QWidget):
	IsRealsimulation_signal = pyqtSignal()

	def __init__(self, parent=None):
		super(Realtime_view, self).__init__(parent)
		self.img3 = None
		self.img2 = None
		self.img1 = None
		self.setWindowTitle("仿生偏振视觉感知与偏振模式重绘")
		self.setWindowModality(Qt.WindowModal)
		self.resize(1103, 832)

		boxQSS = """
							border-radius:5px;
							font-size:10pt;
							font-family:"Times New Roman" , "Microsoft YaHei";
							border-width: 2px;
							border-color:rgb(118, 121, 124);
						 """
		comboxQSS = """
							QComboBox {
										font: 10pt "Times New Roman";
										min-width: 35px;
										min-height:20px;
										border-radius: 15px;
										border:2px solid rgb(118, 121, 124);
										}
							QComboBox:hover {
										/* 鼠标悬浮在QComboBox上时的状态 */
										background-color: rgb(24, 70, 93);
										border:2px solid rgb(61, 174, 233);
										color: white;}
							/* 下拉列表里的颜色 */
							QComboBox QAbstractItemView {
								border: 2px solid rgb(61, 174, 233);/*边框宽度、线形、颜色*/
								border-radius: 15px;/*圆角*/
								min-width: 2em;   /*# 组合框的最小宽度*/
								padding: 1px 2px 1px 2px;  /*针对于组合框中的文本内容*/
								selection-color: rgb(61, 174, 233);
								selection-background-color: rgb(49, 54, 59);
								background-color: rgb(66, 106, 106);/*背景颜色*/
							}
							"""
		labelQSS = """
							QLabel {
									border-radius:10px;
									border: 2px solid rgb(118, 121, 124);
									font-family:Times New Roman;
									font-size:10pt;
									}

							QLabel:hover{
										background-color:#426a6a;
										color:white;
										border: 2px solid rgb(61, 174, 233);
										}
							"""
		buttonQSS = """
								 QPushButton {font-size: 9pt;
									color: #BDC8E2;
									border: 2px solid rgb(118, 121, 124);
									border-radius: 3px;}

								QPushButton:hover {	/* 鼠标悬浮在QPushButton上时的状态 */
									background-color: rgb(66, 106, 106);
									border-color:rgb(61, 174, 233);
									}
								QPushButton:pressed { /* 鼠标按压在QPushButton上时的状态 */
									background-color: #35071f;
									border-color:rgb(61, 174, 233);}
							"""
		self.QVBoxLayout = QVBoxLayout()
		self.Left_VBoxLayout = QVBoxLayout()

		self.QVBoxLayout.addLayout(self.Left_VBoxLayout)
		self.Sum_GBox = QGroupBox()
		self.Sum_GBox.setTitle("图像实时捕获区域")
		self.Sum_GBox.setStyleSheet(boxQSS)
		self.Left_VBoxLayout.addWidget(self.Sum_GBox)

		self.UpAll_VLayout = QVBoxLayout()
		self.Sum_GBox.setLayout(self.UpAll_VLayout)

		self.Up1_HLayout = QHBoxLayout()
		self.Action_Button = QPushButton("开启相机")
		self.Action_Button.setMinimumHeight(40)
		self.Action_Button.setStyleSheet(buttonQSS)
		self.Up1_HLayout.addWidget(self.Action_Button)

		self.Close_Button = QPushButton("关闭相机")
		self.Close_Button.setMinimumHeight(40)
		self.Close_Button.setStyleSheet(buttonQSS)
		self.Up1_HLayout.addWidget(self.Close_Button)

		self.Photo_Button = QPushButton("拍摄")
		self.Photo_Button.setMinimumHeight(40)
		self.Photo_Button.setStyleSheet(buttonQSS)
		self.Up1_HLayout.addWidget(self.Photo_Button)

		self.View_Button = QPushButton("预览")
		self.View_Button.setMinimumHeight(40)
		self.View_Button.setStyleSheet(buttonQSS)
		self.Up1_HLayout.addWidget(self.View_Button)

		self.UpAll_VLayout.addLayout(self.Up1_HLayout)

		self.Up12_HLayout = QHBoxLayout()

		self.Up12L_Spacer = QSpacerItem(255, 10, QSizePolicy.Fixed, QSizePolicy.Expanding)
		self.Up12_HLayout.addSpacerItem(self.Up12L_Spacer)

		self.ImfSavelabel = QLabel("图像保存方式☞")
		self.Up12_HLayout.addWidget(self.ImfSavelabel)

		comboboxItem = ['HOST', 'DB', 'H&DB']
		self.ManagerCombbox = QComboBox()
		self.ManagerCombbox.setMinimumWidth(65)
		self.ManagerCombbox.addItems(comboboxItem)
		self.ManagerCombbox.setStyleSheet(comboxQSS)
		self.Up12_HLayout.addWidget(self.ManagerCombbox)

		self.FilpImgLabel = QLabel("旋转图像☞")
		self.Up12_HLayout.addWidget(self.FilpImgLabel)
		comboboxItem1 = ['不旋转', '左右镜像', '上下镜像', '对角镜像', '旋转90', '旋转180', '旋转270']
		self.FlipCombbox = QComboBox()
		self.FlipCombbox.setMinimumWidth(65)

		self.FlipCombbox.addItems(comboboxItem1)
		self.FlipCombbox.setStyleSheet(comboxQSS)
		self.Up12_HLayout.addWidget(self.FlipCombbox)

		self.Up12R_Spacer = QSpacerItem(255, 10)
		self.Up12_HLayout.addSpacerItem(self.Up12R_Spacer)

		self.UpAll_VLayout.addLayout(self.Up12_HLayout)

		self.Up2_HLayout = QHBoxLayout()
		self.UpAll_VLayout.addLayout(self.Up2_HLayout)

		self.first_box = QGroupBox()
		self.first_Layout = QHBoxLayout()
		self.label1 = QLabel()
		self.label1.setFixedSize(320, 250)
		self.label1.setStyleSheet(labelQSS)
		self.first_Layout.addWidget(self.label1)
		self.first_box.setLayout(self.first_Layout)
		self.Up2_HLayout.addWidget(self.first_box)

		self.two_box = QGroupBox()
		self.two_Layout = QHBoxLayout()
		self.label2 = QLabel()
		self.label2.setStyleSheet(labelQSS)
		self.label2.setFixedSize(320, 250)
		self.two_Layout.addWidget(self.label2)
		self.two_box.setLayout(self.two_Layout)
		self.Up2_HLayout.addWidget(self.two_box)

		self.three_box = QGroupBox()
		self.three_Layout = QHBoxLayout()
		self.label3 = QLabel()
		self.label3.setFixedSize(320, 250)
		self.label3.setStyleSheet(labelQSS)
		self.three_Layout.addWidget(self.label3)
		self.three_box.setLayout(self.three_Layout)
		self.Up2_HLayout.addWidget(self.three_box)

		self.Left_VBoxLayout.addLayout(self.Up2_HLayout)
		self.cameras = QCameraInfo.availableCameras()
		if len(self.cameras) == 3:
			self.first_box.setTitle("相机状态:Already Connected")
			self.two_box.setTitle("相机状态:Already Connected")
			self.three_box.setTitle("相机状态:Already Connected")
		if len(self.cameras) == 2:
			self.first_box.setTitle("相机状态:Already Connected")
			self.two_box.setTitle("相机状态:Already Connected")
			self.three_box.setTitle("相机状态:Not Detected")
		if len(self.cameras) == 1:
			self.first_box.setTitle("相机状态:Already Connected")
			self.two_box.setTitle("相机状态:Not Detected")
			self.three_box.setTitle("相机状态:Not Detected")
		if len(self.cameras) == 0:
			self.first_box.setTitle("相机状态:Not Detected")
			self.two_box.setTitle("相机状态:Not Detected")
			self.three_box.setTitle("相机状态:Not Detected")

		self.Middle_HLayout = QHBoxLayout()
		self.Middle_GBox = QGroupBox()
		self.Middle_GBox.setStyleSheet(boxQSS)
		self.Middle_GBox.setTitle("本地图片上传/捕获预览区域")
		self.Middle_HLayout.addWidget(self.Middle_GBox)

		self.MiddleIN_HLayout = QHBoxLayout()
		self.Middle_GBox.setLayout(self.MiddleIN_HLayout)
		self.Left_VBoxLayout.addWidget(self.Middle_GBox)

		self.first_GBox = QGroupBox()
		self.first_GBox.setAlignment(Qt.AlignCenter)
		self.first_VLayout = QVBoxLayout()
		self.first_VLayout.setAlignment(Qt.AlignCenter)
		self.first_GBox.setLayout(self.first_VLayout)

		self.first_HLayout = QHBoxLayout()
		self.firstChoice_Button = QPushButton("选择本地图片")
		self.firstChoice_Button.setFixedWidth(110)
		self.firstChoice_Button.setStyleSheet(buttonQSS)
		self.first_HLayout.addWidget(self.firstChoice_Button)
		self.first_VLayout.addLayout(self.first_HLayout)

		self.first_Label = QLabel()
		self.first_Label.setFixedSize(320, 250)
		self.first_Label.setScaledContents(True)
		self.first_Label.setStyleSheet(labelQSS)
		self.first_VLayout.addWidget(self.first_Label)
		self.MiddleIN_HLayout.addWidget(self.first_GBox)

		self.two_GBox = QGroupBox()
		self.two_VLayout = QVBoxLayout()
		self.two_GBox.setLayout(self.two_VLayout)

		self.two_HLayout = QHBoxLayout()
		self.twoChoice_Button = QPushButton("选择本地图片")
		self.twoChoice_Button.setFixedWidth(110)
		self.twoChoice_Button.setStyleSheet(buttonQSS)
		self.two_HLayout.addWidget(self.twoChoice_Button)
		self.two_VLayout.addLayout(self.two_HLayout)

		self.two_Label = QLabel()
		self.two_Label.setFixedSize(320, 250)
		self.two_Label.setStyleSheet(labelQSS)
		self.two_VLayout.addWidget(self.two_Label)
		self.MiddleIN_HLayout.addWidget(self.two_GBox)

		self.three_GBox = QGroupBox()
		self.three_VLayout = QVBoxLayout()
		self.three_GBox.setLayout(self.three_VLayout)

		self.three_HLayout = QHBoxLayout()
		self.threeChoice_Button = QPushButton("选择本地图片")
		self.threeChoice_Button.setFixedWidth(110)
		self.threeChoice_Button.setStyleSheet(buttonQSS)
		self.three_HLayout.addWidget(self.threeChoice_Button)
		self.three_VLayout.addLayout(self.three_HLayout)

		self.three_Label = QLabel()
		self.three_Label.setFixedSize(320, 250)
		self.three_Label.setStyleSheet(labelQSS)
		self.three_VLayout.addWidget(self.three_Label)
		self.MiddleIN_HLayout.addWidget(self.three_GBox)

		self.Belowest_HLayout = QHBoxLayout()
		self.Belowest_HLayout.setAlignment(Qt.AlignCenter)
		self.Left_VBoxLayout.addLayout(self.Belowest_HLayout)

		self.Savelabel = QLabel("结果保存☞")
		self.Belowest_HLayout.addWidget(self.Savelabel)

		comboboxItem_manager = ['不保存', '本机', '数据库', '本机和数据库']
		self.SaveCombbox = QComboBox()
		self.SaveCombbox.addItems(comboboxItem_manager)
		self.SaveCombbox.setStyleSheet(comboxQSS)
		self.Belowest_HLayout.addWidget(self.SaveCombbox)

		self.Below1_VBoxLayout = QVBoxLayout()
		self.Below1_VBoxLayout.setAlignment(Qt.AlignCenter)
		self.Left_VBoxLayout.addLayout(self.Below1_VBoxLayout)

		self.end_layout = QHBoxLayout()
		self.Can_view_Button = QPushButton("天空偏振光分布探测")
		self.Can_view_Button.setFixedWidth(130)
		self.Can_view_Button.setFixedHeight(40)
		self.Can_view_Button.setStyleSheet(buttonQSS)
		self.end_layout.addWidget(self.Can_view_Button)

		self.Target_Button = QPushButton("仿生偏振感知")
		self.Target_Button.setFixedWidth(130)
		self.Target_Button.setFixedHeight(40)
		self.Target_Button.setStyleSheet(buttonQSS)
		self.end_layout.addWidget(self.Target_Button)

		self.Below1_VBoxLayout.addLayout(self.end_layout)

		self.dir_Label = QLabel()
		self.dir_Label.setFixedHeight(20)
		self.dir_Label.setAlignment(Qt.AlignLeft)
		self.Left_VBoxLayout.addWidget(self.dir_Label)

		self.setLayout(self.QVBoxLayout)

		self.setup_signal()
		self.center()

		self.currentPath = QDir.currentPath()
		self.currentPath = self.currentPath.replace('/', '\\')

		self.img1path, self.img2path, self.img3path = None, None, None
		self.imgName1, self.imgName2, self.imgName3 = None, None, None
		self.fileName1, self.fileName2, self.fileName3 = None, None, None
		self.choice_img1bool, self.choice_img2bool, self.choice_img3bool = False, False, False

		self.is_camera_opened = False
		self.has_take_photo = False

	def center(self):
		qRect = self.frameGeometry()
		centerPoint = QDesktopWidget().availableGeometry().center()
		qRect.moveCenter(centerPoint)
		self.move(qRect.topLeft())

	def setup_signal(self):
		self.Action_Button.clicked.connect(self.Open_camera_clicked)
		self.Close_Button.clicked.connect(self.Close_camera_clicked)
		self.Photo_Button.clicked.connect(self.SaveImages_clicked)
		self.View_Button.clicked.connect(self.view_photo)

		self.firstChoice_Button.clicked.connect(self.Choice_local_img1)
		self.twoChoice_Button.clicked.connect(self.Choice_local_img2)
		self.threeChoice_Button.clicked.connect(self.Choice_local_img3)
		self.FlipCombbox.activated.connect(self.Flip_Combox_change)
		self.Can_view_Button.clicked.connect(self.Can_view_clicked)
		self.Target_Button.clicked.connect(self.AoP_DoP_Imageview)

	# 初始化摄像头
	def camera_init(self):
		self.camera_init1 = None
		self.camera_init2 = None
		self.camera_init3 = None

		if len(self.cameras) == 1:
			self.camera_init1 = cv2.VideoCapture(0 + cv2.CAP_DSHOW)
		elif len(self.cameras) == 2:
			self.camera_init1 = cv2.VideoCapture(0 + cv2.CAP_DSHOW)
			self.camera_init2 = cv2.VideoCapture(1 + cv2.CAP_DSHOW)
		elif len(self.cameras) == 3:
			self.camera_init1 = cv2.VideoCapture(0 + cv2.CAP_DSHOW)
			self.camera_init2 = cv2.VideoCapture(1 + cv2.CAP_DSHOW)
			self.camera_init3 = cv2.VideoCapture(2 + cv2.CAP_DSHOW)

	# 用QTimer显示摄像头输出画面
	def show_camera(self):
		global success2, view_img2, success3, view_img3
		if not self.is_camera_opened:
			return

		if len(self.cameras) == 3:
			success1, view_img1 = self.camera_init1.read()
			success2, view_img2 = self.camera_init2.read()
			success3, view_img3 = self.camera_init3.read()
		elif len(self.cameras) == 2:
			success1, view_img1 = self.camera_init1.read()
			success2, view_img2 = self.camera_init2.read()
		elif len(self.cameras) == 1:
			success1, view_img1 = self.camera_init1.read()
		else:
			return
		if success1 is not None:
			self.img1 = view_img1
			view_img1 = cv2.resize(view_img1, (int(self.label1.width()), int(self.label1.height())))

			QImgFormat1 = QPixmap.fromImage(QImage(cv2.cvtColor(view_img1, cv2.COLOR_BGR2RGB),
			                                       self.label1.width(),
			                                       self.label1.height(),
			                                       self.label1.width() * 3,
			                                       13))

			self.label1.setPixmap(QImgFormat1)
		if success2 is not None:
			self.img2 = view_img2
			view_img2 = cv2.resize(view_img2, (int(self.label2.width()), int(self.label2.height())))

			QImgFormat2 = QPixmap.fromImage(QImage(cv2.cvtColor(view_img2, cv2.COLOR_BGR2RGB),
			                                       self.label2.width(),
			                                       self.label2.height(),
			                                       self.label2.width() * 3,
			                                       13))

			self.label2.setPixmap(QImgFormat2)
		if success3 is not None:
			self.img3 = view_img3
			view_img3 = cv2.resize(view_img3, (int(self.label3.width()), int(self.label3.height())))

			QImgFormat3 = QPixmap.fromImage(QImage(cv2.cvtColor(view_img3, cv2.COLOR_BGR2RGB),
			                                       self.label3.width(),
			                                       self.label3.height(),
			                                       self.label3.width() * 3,
			                                       13))
			self.label3.setPixmap(QImgFormat3)

	# 开始QTimer定时器
	def Open_camera_clicked(self):
		self.camera_init()
		timer_camera1 = QTimer(self)
		timer_camera1.timeout.connect(self.show_camera)
		timer_camera1.start(25)

		self.is_camera_opened = ~self.is_camera_opened
		if self.is_camera_opened:
			self.Action_Button.setEnabled(False)
			self.Close_Button.setEnabled(True)
			self.Photo_Button.setEnabled(True)
			self.View_Button.setEnabled(True)

	# 关闭摄像头
	def Close_camera_clicked(self):
		self.is_camera_opened = ~self.is_camera_opened

		if not self.is_camera_opened:
			self.camera_init1.release()
			self.camera_init2.release()
			self.camera_init3.release()

			self.Action_Button.setEnabled(True)
			self.Close_Button.setEnabled(False)
			self.Photo_Button.setEnabled(False)
			self.View_Button.setEnabled(True)

	# 保存图像
	def SaveImages_clicked(self):
		currentDateTime = QDateTime.currentDateTime().toString("yyyy-MM-dd HH-mm-ss")
		img0_name = currentDateTime + ' 0.bmp'
		img60_name = currentDateTime + ' 60.bmp'
		img120_name = currentDateTime + ' 120.bmp'

		# 实例化捕获图像的路径+名称
		if len(self.cameras) == 1:
			self.fileName1 = './Image/' + img0_name
			print("fileName: ", self.fileName1)
		elif len(self.cameras) == 2:
			self.fileName1 = './Image/' + img0_name
			self.fileName2 = './Image/' + img60_name
			print("fileName: ", self.fileName1)
			print("fileName: ", self.fileName2)
		elif len(self.cameras) == 3:
			self.fileName1 = './Image/' + img0_name
			self.fileName2 = './Image/' + img60_name
			self.fileName3 = './Image/' + img120_name
		else:
			return

		# 判断保存方式
		# 1、本地
		if self.ManagerCombbox.currentText() == "Host":
			if len(self.cameras) == 1:
				cv2.imencode('.bmp', self.img1)[1].tofile(self.fileName1)
				self.has_take_photo = True
			elif len(self.cameras) == 2:
				cv2.imencode('.bmp', self.img1)[1].tofile(self.fileName1)
				cv2.imencode('.bmp', self.img2)[1].tofile(self.fileName2)
				self.has_take_photo = True
			elif len(self.cameras) == 3:
				cv2.imencode('.bmp', self.img1)[1].tofile(self.fileName1)
				cv2.imencode('.bmp', self.img2)[1].tofile(self.fileName2)
				cv2.imencode('.bmp', self.img3)[1].tofile(self.fileName3)
				self.has_take_photo = True
			else:
				return
		# 2、数据库
		elif self.ManagerCombbox.currentText() == "DB":
			con = connect("./db/Image_database.db")
			cur = con.cursor()
			symbol = 'pictureTable'
			try:
				cur.execute(
					"create table IF NOT EXISTS %s(picName TEXT, width INTEGER, height INTEGER, image_bytes BLOB)" % symbol)
				con.commit()
				pass
			except Exception as e:
				print(e, "create table failed")
			if len(self.cameras) == 1:
				cv2.imencode('.bmp', self.img1)[1].tofile(self.fileName1)
				self.has_take_photo = True

				sql1 = f"INSERT OR REPLACE INTO pictureTable (picName, width, height, image_bytes) VALUES (?, ?, ?, ?);"

				img1 = open(self.fileName1)
				img_buffer1 = BytesIO()
				img1.save(img_buffer1, format='JPEG')
				byte_data1 = img_buffer1.getvalue()

				base64_byte1 = b64encode(byte_data1)
				cur.execute(sql1,
				            (img0_name, int(self.label1.width()), int(self.label1.height()), base64_byte1))
				con.commit()
				remove(self.fileName1)
			elif len(self.cameras) == 2:
				cv2.imencode('.bmp', self.img1)[1].tofile(self.fileName1)
				cv2.imencode('.bmp', self.img2)[1].tofile(self.fileName2)
				self.has_take_photo = True

				sql1 = f"INSERT OR REPLACE INTO pictureTable (picName, width, height, image_bytes) VALUES (?, ?, ?, ?);"
				sql2 = f"INSERT OR REPLACE INTO pictureTable (picName, width, height, image_bytes) VALUES (?, ?, ?, ?);"

				img1 = open(self.fileName1)
				img2 = open(self.fileName2)

				img_buffer1 = BytesIO()
				img_buffer2 = BytesIO()

				img1.save(img_buffer1, format='JPEG')
				img2.save(img_buffer2, format='JPEG')

				byte_data1 = img_buffer1.getvalue()
				byte_data2 = img_buffer2.getvalue()

				base64_byte1 = b64encode(byte_data1)
				base64_byte2 = b64encode(byte_data2)

				cur.execute(sql1,
				            (img0_name, int(self.label1.width()), int(self.label1.height()), base64_byte1))
				cur.execute(sql2,
				            (img60_name, int(self.label1.width()), int(self.label1.height()), base64_byte2))
				con.commit()
				remove(self.fileName1)
				remove(self.fileName2)
			elif len(self.cameras) == 3:
				cv2.imencode('.bmp', self.img1)[1].tofile(self.fileName1)
				cv2.imencode('.bmp', self.img2)[1].tofile(self.fileName2)
				cv2.imencode('.bmp', self.img3)[1].tofile(self.fileName3)
				self.has_take_photo = True

				sql1 = f"INSERT OR REPLACE INTO pictureTable (picName, width, height, image_bytes) VALUES (?, ?, ?, ?);"
				sql2 = f"INSERT OR REPLACE INTO pictureTable (picName, width, height, image_bytes) VALUES (?, ?, ?, ?);"
				sql3 = f"INSERT OR REPLACE INTO pictureTable (picName, width, height, image_bytes) VALUES (?, ?, ?, ?);"

				img1 = open(self.fileName1)
				img2 = open(self.fileName2)
				img3 = open(self.fileName3)

				img_buffer1 = BytesIO()
				img_buffer2 = BytesIO()
				img_buffer3 = BytesIO()

				img1.save(img_buffer1, format='JPEG')
				img2.save(img_buffer2, format='JPEG')
				img3.save(img_buffer3, format='JPEG')

				byte_data1 = img_buffer1.getvalue()
				byte_data2 = img_buffer2.getvalue()
				byte_data3 = img_buffer3.getvalue()

				base64_byte1 = b64encode(byte_data1)
				base64_byte2 = b64encode(byte_data2)
				base64_byte3 = b64encode(byte_data3)

				cur.execute(sql1,
				            (img0_name, int(self.label1.width()), int(self.label1.height()), base64_byte1))
				cur.execute(sql2,
				            (img60_name, int(self.label1.width()), int(self.label1.height()), base64_byte2))
				cur.execute(sql3,
				            (img120_name, int(self.label1.width()), int(self.label1.height()), base64_byte3))
				con.commit()
				remove(self.fileName1)
				remove(self.fileName2)
				remove(self.fileName3)
			else:
				return
		# 3、本地和数据库同时保存
		else:
			con = connect("db/Image_database.db")
			cur = con.cursor()
			symbol = 'pictureTable'
			try:
				cur.execute(
					"create table IF NOT EXISTS %s(picName TEXT, width INTEGER, height INTEGER, image_bytes BLOB)" % symbol)
				con.commit()
				pass
			except Exception as e:
				print(e, "create table failed")

			if len(self.cameras) == 1:
				cv2.imencode('.bmp', self.img1)[1].tofile(self.fileName1)
				self.has_take_photo = True

				sql1 = f"INSERT OR REPLACE INTO pictureTable (picName, width, height, image_bytes) VALUES (?, ?, ?, ?);"

				img1 = open(self.fileName1)
				img_buffer1 = BytesIO()
				img1.save(img_buffer1, format='JPEG')
				byte_data1 = img_buffer1.getvalue()

				base64_byte1 = b64encode(byte_data1)
				cur.execute(sql1,
				            (img0_name, int(self.label1.width()), int(self.label1.height()), base64_byte1))
				con.commit()
			elif len(self.cameras) == 2:
				cv2.imencode('.bmp', self.img1)[1].tofile(self.fileName1)
				cv2.imencode('.bmp', self.img2)[1].tofile(self.fileName2)
				self.has_take_photo = True

				sql1 = f"INSERT OR REPLACE INTO pictureTable (picName, width, height, image_bytes) VALUES (?, ?, ?, ?);"
				sql2 = f"INSERT OR REPLACE INTO pictureTable (picName, width, height, image_bytes) VALUES (?, ?, ?, ?);"

				img1 = open(self.fileName1)
				img2 = open(self.fileName2)

				img_buffer1 = BytesIO()
				img_buffer2 = BytesIO()

				img1.save(img_buffer1, format='JPEG')
				img2.save(img_buffer2, format='JPEG')

				byte_data1 = img_buffer1.getvalue()
				byte_data2 = img_buffer2.getvalue()

				base64_byte1 = b64encode(byte_data1)
				base64_byte2 = b64encode(byte_data2)

				cur.execute(sql1,
				            (img0_name, int(self.label1.width()), int(self.label1.height()), base64_byte1))
				cur.execute(sql2,
				            (img60_name, int(self.label1.width()), int(self.label1.height()), base64_byte2))

				con.commit()
			elif len(self.cameras) == 3:
				cv2.imencode('.bmp', self.img1)[1].tofile(self.fileName1)
				cv2.imencode('.bmp', self.img2)[1].tofile(self.fileName2)
				cv2.imencode('.bmp', self.img3)[1].tofile(self.fileName3)
				self.has_take_photo = True

				sql1 = f"INSERT OR REPLACE INTO pictureTable (picName, width, height, image_bytes) VALUES (?, ?, ?, ?);"
				sql2 = f"INSERT OR REPLACE INTO pictureTable (picName, width, height, image_bytes) VALUES (?, ?, ?, ?);"
				sql3 = f"INSERT OR REPLACE INTO pictureTable (picName, width, height, image_bytes) VALUES (?, ?, ?, ?);"

				img1 = open(self.fileName1)
				img2 = open(self.fileName2)
				img3 = open(self.fileName3)

				img_buffer1 = BytesIO()
				img_buffer2 = BytesIO()
				img_buffer3 = BytesIO()

				img1.save(img_buffer1, format='JPEG')
				img2.save(img_buffer2, format='JPEG')
				img3.save(img_buffer3, format='JPEG')

				byte_data1 = img_buffer1.getvalue()
				byte_data2 = img_buffer2.getvalue()
				byte_data3 = img_buffer3.getvalue()

				base64_byte1 = b64encode(byte_data1)
				base64_byte2 = b64encode(byte_data2)
				base64_byte3 = b64encode(byte_data3)

				cur.execute(sql1,
				            (img0_name, int(self.label1.width()), int(self.label1.height()), base64_byte1))
				cur.execute(sql2,
				            (img60_name, int(self.label1.width()), int(self.label1.height()), base64_byte2))
				cur.execute(sql3,
				            (img120_name, int(self.label1.width()), int(self.label1.height()), base64_byte3))
				con.commit()
			else:
				return

	# 旋转图像函数
	def ComboBox_Flip_Image(self, img):
		transform = QTransform()
		IMG = QImage(img)
		if self.FlipCombbox.currentText() == '不旋转':
			IMG = IMG
		elif self.FlipCombbox.currentText() == '左右镜像':
			IMG = IMG.mirrored(True, False)
		elif self.FlipCombbox.currentText() == '上下镜像':
			IMG = IMG.mirrored(False, True)
		elif self.FlipCombbox.currentText() == '对角镜像':
			IMG = IMG.mirrored(True, True)
		elif self.FlipCombbox.currentText() == '旋转90':
			transform.rotate(90)
			IMG = IMG.transformed(transform)
		elif self.FlipCombbox.currentText() == '旋转180':
			transform.rotate(180)
			IMG = IMG.transformed(transform)
		elif self.FlipCombbox.currentText() == '旋转270':
			transform.rotate(270)
			IMG = IMG.transformed(transform)
		return IMG

	# 预览图像
	def view_photo(self):
		if self.has_take_photo is True and len(self.cameras) == 1:
			self.choice_img1bool = True
			self.img1path = self.fileName1
			IMG = self.ComboBox_Flip_Image(self.img1path)
			img1 = QPixmap(IMG)
			H1 = self.first_Label.height()
			W1 = self.first_Label.width()
			img1.scaled(W1, H1, Qt.KeepAspectRatio, Qt.SmoothTransformation)
			self.first_Label.setPixmap(img1)
		elif self.has_take_photo is True and len(self.cameras) == 2:
			self.choice_img1bool = True
			self.choice_img2bool = True
			self.img1path = self.fileName1
			IMG = self.ComboBox_Flip_Image(self.img1path)
			img1 = QPixmap(IMG)
			H1 = self.first_Label.height()
			W1 = self.first_Label.width()
			img1.scaled(W1, H1, Qt.KeepAspectRatio, Qt.SmoothTransformation)
			self.first_Label.setPixmap(img1)

			self.img2path = self.fileName2
			IMG = self.ComboBox_Flip_Image(self.img2path)
			img2 = QPixmap(IMG)
			H2 = self.two_Label.height()
			W2 = self.two_Label.width()
			img1.scaled(W2, H2, Qt.KeepAspectRatio, Qt.SmoothTransformation)
			self.two_Label.setPixmap(img2)
		elif self.has_take_photo is True and len(self.cameras) == 3:
			self.choice_img1bool = True
			self.choice_img2bool = True
			self.choice_img3bool = True
			self.img1path = self.fileName1

			pix1 = QPixmap(self.img1path)
			self.first_Label.setScaledContents(True)
			self.first_Label.setPixmap(pix1)

			self.img2path = self.fileName2
			pix2 = QPixmap(self.img2path)
			self.two_Label.setScaledContents(True)
			self.two_Label.setPixmap(pix2)

			self.img3path = self.fileName3
			pix3 = QPixmap(self.img3path)
			self.three_Label.setScaledContents(True)
			self.three_Label.setPixmap(pix3)
		else:
			print(QMessageBox.warning(self, '警告', '还没有拍摄照片，无法预览！', QMessageBox.Yes, QMessageBox.Yes))

	# 选择本地图像1
	def Choice_local_img1(self):
		self.choice_img1bool = False
		self.imgName1, imgType = QFileDialog.getOpenFileName(self, "打开图片", "",
		                                                     "*All Files(*);;BMP(*.bmp);;JPG(*.jpg);;CR2(*.cr2)")
		bmp1 = QPixmap(self.imgName1).scaled(self.first_Label.width(), self.first_Label.height())
		self.first_Label.setPixmap(bmp1)

	# 选择本地图像2
	def Choice_local_img2(self):
		self.choice_img2bool = False
		self.imgName2, imgType = QFileDialog.getOpenFileName(self, "打开图片", "",
		                                                     "*All Files(*);;BMP(*.bmp);;JPG(*.jpg);;CR2(*.cr2)")
		bmp2 = QPixmap(self.imgName2).scaled(self.two_Label.width(), self.two_Label.height())
		self.two_Label.setPixmap(bmp2)

	# 选择本地图像3
	def Choice_local_img3(self):
		self.choice_img3bool = False
		self.imgName3, imgType = QFileDialog.getOpenFileName(self, "打开图片", "",
		                                                     "*All Files(*);;BMP(*.bmp);;JPG(*.jpg);;CR2(*.cr2)")
		bmp3 = QPixmap(self.imgName3).scaled(self.three_Label.width(), self.three_Label.height())
		self.three_Label.setPixmap(bmp3)

	# 改变下拉栏的时候旋转图像
	def Flip_Combox_change(self):
		try:
			img1 = self.first_Label.pixmap().toImage()
			img1 = self.ComboBox_Flip_Image(img1)
			img1 = QPixmap(img1)
			self.first_Label.setPixmap(img1)

			img2 = self.two_Label.pixmap().toImage()
			img2 = self.ComboBox_Flip_Image(img2)
			img2 = QPixmap(img2)
			self.two_Label.setPixmap(img2)

			img3 = self.three_Label.pixmap().toImage()
			img3 = self.ComboBox_Flip_Image(img3)
			img3 = QPixmap(img3)
			self.three_Label.setPixmap(img3)
		except AttributeError as a:
			self.FlipCombbox.setCurrentText("不旋转")
			print(QMessageBox.warning(self, '警告', "旋转图像前，请先上传图像！", QMessageBox.Yes, QMessageBox.Yes))

	# 大气偏振模式探测
	def judge_dir(self, img_bool, name_str, file_str):
		if not img_bool:
			img = name_str
		else:
			if file_str is not None:
				img = self.fileName3
			else:
				print(QMessageBox.warning(self, '警告', '请输入完整的地址', QMessageBox.Yes, QMessageBox.Yes))
				return
		return img

	def Can_view_clicked(self):
		img1 = self.judge_dir(self.choice_img1bool, self.imgName1, self.fileName1)
		img2 = self.judge_dir(self.choice_img2bool, self.imgName2, self.fileName2)
		img3 = self.judge_dir(self.choice_img3bool, self.imgName3, self.fileName3)

		FLIP_PHOTO = self.FlipCombbox.currentText()
		SAVE_RESULT = self.SaveCombbox.currentText()
		print("开始大气偏振探测")
		self.widget = Loc_Sim_Matplot_Dialog(img3, img1, img2, FLIP_PHOTO, SAVE_RESULT)
		self.widget.show()
		print("结束大气偏振探测")

	# 目标感知
	def AoP_DoP_Imageview(self):
		try:
			img1 = self.judge_dir(self.choice_img1bool, self.imgName1, self.fileName1)
			img2 = self.judge_dir(self.choice_img2bool, self.imgName2, self.fileName2)
			img3 = self.judge_dir(self.choice_img3bool, self.imgName3, self.fileName3)
			rcParams['font.sans-serif'] = ['SimHei']
			rcParams['axes.unicode_minus'] = False
			SAVE_RESULT = self.SaveCombbox.currentText()
			print("开始目标探测")
			self.widget = Target_view(img1, img2, img3, SAVE_RESULT)
			self.widget.show()
			print("结束目标探测")
		except AttributeError as a:
			print(a)
		except RuntimeWarning as a:
			print(a)


if __name__ == '__main__':
	from sys import argv, exit

	rcParams['font.sans-serif'] = ['SimHei']
	rcParams['axes.unicode_minus'] = False
	app = QApplication(argv)
	app.setStyleSheet(load_stylesheet_pyqt5())

	demo = Realtime_view()
	demo.show()
	exit(app.exec_())
